package top.fyukina.fymil.parsers;

import org.dom4j.CDATA;
import org.dom4j.Element;
import org.dom4j.Text;
import top.fyukina.fymil.elements.Environment;

public class StringParser implements Parser<String> {
    @Override
    public String parse(Element tag, Environment env) {
        StringBuilder sb = new StringBuilder();
        tag.content().iterator().forEachRemaining(node -> {
            if (node instanceof Text t) {
                sb.append(realTrim(t.getText()));
            } else if (node instanceof CDATA cdata) {
                sb.append(cdata.getText().trim());
            } else if (node instanceof Element el0) {
                switch (el0.getName()) {
                    case "br" -> sb.append(System.lineSeparator());
                    case "w" -> sb.append(" ");
                    default -> sb.append(env.reg().expParser.parse(el0, env));
                }
            }
        });
        return sb.toString();
    }
    public String realTrim(String str) {
        return str.trim().replaceAll("\\s+", "");
    }
    @Override
    public ParserType registerName() {
        return ParserType.STR;
    }
}